package core

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"gintify/model"
	"time"
)

var (
	// 以下值均从viper中读取
	jwtKey string = CF.Jwt.Key         // "secret_hard_to_guess"
	jwtIssuer string = CF.Jwt.Issuer   //"github.com/kessil/gintify"
	jwtSubject string = CF.Jwt.Subject //"user token"
	expireDuration time.Duration = time.Minute * CF.Jwt.Duration
)

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

func NewJwt() {
	jwtKey = CF.Jwt.Key         // "secret_hard_to_guess"
	jwtIssuer = CF.Jwt.Issuer   //"github.com/kessil/gintify"
	jwtSubject = CF.Jwt.Subject //"user token"
	expireDuration = time.Minute * CF.Jwt.Duration
}

func ReleaseToken(user model.SysUser) (string, error) {
	expireTime := time.Now().Add(expireDuration)
	fmt.Println(time.Now().Unix())
	fmt.Println(expireTime.Unix())
	fmt.Println(expireDuration)
	claims := &Claims{
		UserId:         user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt:expireTime.Unix(),
			IssuedAt: time.Now().Unix(),
			Issuer: jwtIssuer,
			Subject: jwtSubject,
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte(jwtKey))
	if err != nil{
		return "", err
	}
	return tokenString, nil
}

func ParseToken(tokenString string)(*jwt.Token, *Claims, error) {
	Claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token)(i interface{}, err error){
		return []byte(jwtKey), nil
	})
	return token, Claims, err
}